//
//  VaccinationController.m
//  Cabinet
//
//  Created by Florent Montsegur on 12/07/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "VaccinationController.h"
#import "Person.h"
#import "SearchVaccinController.h"
#import "SearchRankController.h"



@implementation VaccinationController
@synthesize mNom;
@synthesize mPrenom;
@synthesize mAge;
@synthesize mNaissance;
@synthesize mVaccinationDate;
@synthesize mRappelDate;
@synthesize mVaccinNom;
@synthesize mVaccinCode;
@synthesize mLot;
@synthesize mRang;
@synthesize mManagedObjectContext;
@synthesize mEnfant;
@synthesize mMadame;
@synthesize mMonsieur;
@synthesize mMademoiselle;
@synthesize mVacinationsHistorique;
@synthesize mRangEntity;
@synthesize mVaccinEntity;
@synthesize mVaccinationEntity;
@synthesize mEffacerRappel;



- (id)initWithWindow:(NSWindow *)window
{
    self = [super initWithWindow:window];
    if (self) {
        // Initialization code here.
        
    }
    
    return self;
}

- (NSString*)windowNibName
{
	return @"VaccinationView";
}



- (void)windowDidLoad
{
    [super windowDidLoad];
    
    // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.    
    [self showPerson:mPerson];
}


- (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView{
    return [mVacinations count];
}

- (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex{
    
    if( rowIndex >= [mVacinations count])
        return @"";
    
    Vaccination *vac = [mVacinations objectAtIndex:rowIndex];
    
    if( [[aTableColumn identifier] caseInsensitiveCompare:@"date"] == NSOrderedSame ){
        return [[vac Date] descriptionWithCalendarFormat:@"%d/%m/%y" timeZone:nil locale:[[NSUserDefaults standardUserDefaults] dictionaryRepresentation]];
    }
    
    if( [[aTableColumn identifier] caseInsensitiveCompare:@"vaccin"] == NSOrderedSame )
        return [[vac Vaccin] Nom];    
    
    if( [[aTableColumn identifier] caseInsensitiveCompare:@"rappel"] == NSOrderedSame ){
        NSDate *minval = [NSCalendarDate dateWithString:@"1870-01-01 00:00:00 +0000"];
        
        if(![[vac Rappel] isEqualToDate:minval]) 
            return [[vac Rappel] descriptionWithCalendarFormat:@"%d/%m/%y" timeZone:nil locale:[[NSUserDefaults standardUserDefaults] dictionaryRepresentation]];
    }
    
    if( [[aTableColumn identifier] caseInsensitiveCompare:@"rang"] == NSOrderedSame ){
         return [vac Rang];    
    }
    
    return @"";
}


- (IBAction)okAction:sender
{
    [mPerson setSexe:[self getSelectedSex]];
    
    Vaccination *vacc = [[Vaccination alloc] initWithEntity:mVaccinationEntity insertIntoManagedObjectContext:[self mManagedObjectContext]];
    
    [self fillVaccination:vacc];
    
    [[self mManagedObjectContext] commitEditing];
    
    
    [self closeWindow];
}


- (IBAction)annulerAction:sender
{    
    [self closeWindow];
}


- (void) closeWindow
{
    [[self window] orderOut:nil];
    [NSApp stopModal];
}

- (IBAction)searchRankAction:sender
{
    NSLog(@"On SearchRank");
    
    SearchRankController *wnd = [[SearchRankController alloc] init];
    [wnd setMManagedObjectContext:[self mManagedObjectContext]];
    
    NSFetchRequest *request = [[NSFetchRequest alloc] init] ;
    [request setEntity:mRangEntity];
    
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Label" ascending:YES];
    NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor, nil];  
    [request setSortDescriptors:sortDescriptors];  
    
    NSString * begin = [mRang stringValue];
    if( (begin != nil) && ([begin length]>0) )
    {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Label BEGINSWITH[cd] %@", begin];
        [request setPredicate:predicate];
    }
    
    NSArray * result = [[self mManagedObjectContext] executeFetchRequest:request error:nil];
    [wnd setRanks:result];
    
    [wnd withParentWindow:[self window]];
    
    if( [wnd returnCode] == NSOKButton )
    {
        // afficher le patient
        NSLog(@"On NSOKButton");
        
        Rang *d = [wnd selectedRank];
        if(d!=nil)
            [mRang setStringValue:[d Label]];
    }
    
    
}

- (IBAction)searchVaccinAction:sender
{
    NSLog(@"On SearchVaccin");
    
    SearchVaccinController *wnd = [[SearchVaccinController alloc] init];
    [wnd setMManagedObjectContext:[self mManagedObjectContext]];
    [wnd setMVaccinationEntity:[self mVaccinationEntity]];
    
    NSFetchRequest *request = [[NSFetchRequest alloc] init] ;
    [request setEntity:mVaccinEntity];
    
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Nom" ascending:YES];
    NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor, nil];  
    [request setSortDescriptors:sortDescriptors];  
    
    NSString * begin = [mVaccinNom stringValue];
    if( (begin != nil) && ([begin length]>0) )
    {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Nom BEGINSWITH[cd] %@", begin];
        [request setPredicate:predicate];
    }
    
    NSArray * result = [[self mManagedObjectContext] executeFetchRequest:request error:nil];
    [wnd setVaccins:result];
    
    [wnd withParentWindow:[self window]];
    
    if( [wnd returnCode] == NSOKButton )
    {
        // afficher le patient
        NSLog(@"On NSOKButton");
        
        Vaccin *d = [wnd selectedVaccin];
        if(d!=nil)
        {
            [mVaccinNom setStringValue:[d Nom]];
            [mVaccinCode setStringValue:[[d Type] stringValue]];
        }
    }
    
    
}

-(void) setPerson:(Person*)aPerson
{
    
    mPerson = aPerson;
    
    [self showPerson:mPerson];
}

- (void) showPerson:(Person*)aPerson
{
    if(aPerson == nil)
        return;
        
    [[self mNom] setStringValue:[aPerson Nom]];
    [[self mPrenom] setStringValue:[aPerson Prenom]];
    [[self mNaissance] setDateValue:[aPerson Naissance] ];
    
    [self setSelectedSex:[aPerson Sexe]];
    
    NSDate *minval = [NSCalendarDate dateWithString:@"1870-01-01 00:00:00 +0000"];
    if( ![[aPerson Naissance] isEqualToDate:minval] )
    {
        NSInteger age = [aPerson calculAge];
        [[self mAge] setStringValue:[NSString stringWithFormat:@"%ld an%@", age, (age>1?@"s":@"")]];
    }
    else
        [[self mAge] setStringValue:@""];
    
    NSDate *now = [NSDate date];
    [[self mVaccinationDate] setDateValue:now];
    
    NSDate *endDate = [now dateByAddingTimeInterval:((NSTimeInterval)5*365*60*60*24)];
    [[self mRappelDate] setDateValue:endDate];
    
    // set historique
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Date" ascending:NO];
    NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
    
    mVacinations = [[mPerson Vaccinations] sortedArrayUsingDescriptors:sortDescriptors];
    
    [mVacinationsHistorique reloadData];
    
    [[self mVaccinNom] setStringValue:@""];
    [[self mVaccinCode] setStringValue:@""];
    [[self mRang] setStringValue:@""];
    [[self mLot] setStringValue:@""];
}

-(void) setSelectedSex:(NSNumber*)aSexValue
{
    [mMadame setIntValue:([aSexValue intValue] == Madame ? 1 : 0)];
    [mMademoiselle setIntValue:([aSexValue intValue] == Mademoiselle ? 1 : 0)];
    [mMonsieur setIntValue:([aSexValue intValue] == Monsieur ? 1 : 0)];
    [mEnfant setIntValue:([aSexValue intValue] == Enfant ? 1 : 0)];
}

-(NSNumber*) getSelectedSex
{
    if([mMadame intValue] == 1)
        return [NSNumber numberWithInteger:Madame];
    
    if([mMademoiselle intValue] == 1)
        return [NSNumber numberWithInteger:Mademoiselle];
    
    if([mMonsieur intValue] == 1)
        return [NSNumber numberWithInteger:Monsieur];
    
    return [NSNumber numberWithInteger:Enfant];
}

- (void) fillVaccination:(Vaccination*)aVaccination{
    
    NSString* nom = [self formatInput:mVaccinNom];
    NSString* code = [self formatInput:mVaccinCode];
    NSString* rang = [self formatInput:mRang];
    
    Vaccin *v = [self getVaccin:nom];
    Rang *r = [self getRang:rang];
    
    if(v == nil)
    {
        v = [[Vaccin alloc] initWithEntity:mVaccinEntity insertIntoManagedObjectContext:[self mManagedObjectContext]];
        [v setNom:nom];
        
        NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
        [f setNumberStyle:NSNumberFormatterDecimalStyle];
        [v setType:[f numberFromString:code]];
        
        [aVaccination setVaccin:v];
    }
    else
        [aVaccination setVaccin:v];
    
    if(r == nil)
    {
        // create new rank for next search
        r = [[Rang alloc] initWithEntity:mRangEntity insertIntoManagedObjectContext:[self mManagedObjectContext]];
        [r setLabel:rang];
    }
    
    [aVaccination setRang:rang];
    [aVaccination setDate:[[self mVaccinationDate] dateValue]];
    [aVaccination setLot:[self formatInput:mLot]];
    [aVaccination setRappel:[[self mRappelDate] dateValue]];
    [aVaccination setPerson:mPerson];
}

- (Vaccin*)getVaccin:(NSString*)aNom
{
    NSFetchRequest *request = [[NSFetchRequest alloc] init] ;
    [request setEntity:mVaccinEntity];
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(Nom = %@)", aNom];
    [request setPredicate:predicate];
    
    NSArray * result = [[self mManagedObjectContext] executeFetchRequest:request error:nil];
    
    if([result count]<=0)
        return nil;
    
    return [result objectAtIndex:0];
}

- (Rang*)getRang:(NSString*)aNom
{
    NSFetchRequest *request = [[NSFetchRequest alloc] init] ;
    [request setEntity:mRangEntity];
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(Label = %@)", aNom];
    [request setPredicate:predicate];
    
    NSArray * result = [[self mManagedObjectContext] executeFetchRequest:request error:nil];
    
    if([result count]<=0)
        return nil;
    
    return [result objectAtIndex:0];
}


- (NSString*) formatInput:(NSTextField*)aTextField {
    if( aTextField == nil )
        return @"";
    
    if( [aTextField stringValue] == nil )
        return @"";
    
    return [NSString stringWithFormat:@"%@", [aTextField stringValue]];
}

- (IBAction)effacerRappel:sender{
    NSInteger rowIndex = [[self mVacinationsHistorique] selectedRow];
    if(rowIndex <0 )
        return;
    
    Vaccination *vac = [mVacinations objectAtIndex:rowIndex];
    if(vac == nil)
        return;
    
    [vac setRappel:[NSCalendarDate dateWithString:@"1870-01-01 00:00:00 +0000"]];
    [[self mVacinationsHistorique] reloadData];
}

@end
